$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'monitor/job/list',
        datatype: "json",
        colModel: [			
			{ label: '任务名称', name: 'job_name', width: 45 },
			{ label: '爬取间隔', name: 'scrape_interval', width: 75 },
            { label: '爬取超时', name: 'scrape_timeout', sortable: false, width: 75 },
			{ label: 'metric路径', name: 'metrics_path', width: 90 },
			{ label: '使用数据中心的时间戳', name: 'honor_timestamps', width: 100, formatter: function(value, options, row){
                    return value === true ?
                        '<span class="label label-info">是</span>' :
                        '<span class="label label-info">否</span>';
                }},
			{ label: '请求协议', name: 'scheme', width: 60},
			{ label: '爬取地址', name: 'static_configs', width: 60,formatter: function(value, options, row){
                    let result = "";
                    if(row.static_configs && row.static_configs.length > 0) {
                        let targets = row.static_configs[0].targets
                        for (let i = 0; i < targets.length; i++) {
                            result += targets[i] + "<br>"
                        }
                        result = result.substr(0,result.length-4)
                        return result;
                    }

                }}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            "id": "rn"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        },
        loadComplete:function(data){
            vm.jobList = data
        }
    });
});
var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title:null,
        roleList:{},
        jobList:null,
        job:{
            job_name: null, // 任务名称
            scrape_interval: null, // 爬取间隔
            scrape_timeout: null, // 爬取超时
            metrics_path: null, // metric路径
            honor_timestamps: null, // 是否使用数据中的时间戳
            scheme: null, // 请求协议
            static_configs: [{
                targets: [],
                labels: {}
            }] // 静态配置
        },
        addOrUpdate: "add"
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.addOrUpdate = "add";
            vm.showList = false;
            vm.title = "新增";
            vm.roleList = {};
            vm.job = {
                job_name: null, // 任务名称
                scrape_interval: null, // 爬取间隔
                scrape_timeout: null, // 爬取超时
                metrics_path: null, // metric路径
                honor_timestamps: null, // 是否使用数据中的时间戳
                scheme: null, // 请求协议
                static_configs: [{
                    targets:[],
                    labels:{}
                }] // 静态配置
            };
        },
        // 修改
        update: function () {
            vm.addOrUpdate = "update"
            var rowNum = getSelectedRow(); // 获取当前选择行的行号
            if(rowNum == null){
                return ;
            }

            vm.showList = false;
            vm.title = "修改";
            vm.job = vm.jobList[rowNum-1];
        },
        del: function () {
            var rowNum = getSelectedRow(); // 获取当前选择行的行号
            if(rowNum == null){
                return ;
            }
            let job_name = vm.jobList[rowNum-1].job_name;
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "monitor/job/static/delete",
                    contentType: "application/json",
                    data: JSON.stringify(job_name),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function () {
            var url = vm.addOrUpdate == "add" ? "monitor/job/static/save" : "monitor/job/static/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.job),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{page:page}).trigger("reloadGrid");
        },
        // 表单中，根据索引移除一个target
        removeTarget: function(index) {
            vm.job.static_configs[0].targets.splice(index,1);
        },
        // 表单中，向targets中添加一个空对象
        addTarget: function() {
            vm.job.static_configs[0].targets.push(null)
        },
        // 表单中，根据索引移除一个label
        removeLabel: function(key) {
            vm.$delete(vm.job.static_configs[0].labels,key);
        },
        // 表单中，向labelss中添加一个空对象
        addLabel: function() {
            let _vm = vm
            // 获取labels中键值个数
            let index = Object.keys(vm.job.static_configs[0].labels).length
            layer.prompt(
                {title: '请输入标签key'},
                function(val, index){
                if (_vm.job.static_configs[0].labels.hasOwnProperty(val)){
                    alert("标签key已存在");
                    return;
                }
                // 插入一个示例键值 使用$set触发双向绑定
                _vm.$set(_vm.job.static_configs[0].labels, val, "value"+index)
                layer.close(index);
            });
        },
        modifyLabel: function(key,value) {
            vm.$set(vm.job.static_configs[0].labels, key, value)
            console.info(key,"======", value);
            console.info(vm.job.static_configs[0].labels[key]);
        },
        setTarget: function(value, index){
            vm.job.static_configs[0].targets[index] = value
        }
    }
});